package com.sright.bcard.common.service.share.utils;

import java.io.*;

/**
 * Created by pengcheng091 on 2015/8/22 0022.
 */
public class InputStreamTool {
    public static String convertStreamToString(InputStream is) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }

    public static String convertStreamToString(InputStream is, String charsetName) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, charsetName));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }

    public static String convertImageFileToString(InputStream in) throws IOException {
        byte[] data = new byte[in.available()];
        in.read(data);
        return Base64Tool.encode(data);
    }

    public static byte[] getStreamBytes(InputStream is) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = is.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        byte[] b = baos.toByteArray();
        is.close();
        baos.close();
        return b;
    }

    public static byte[] convertStreamToBytes(InputStream in) throws IOException {
        byte[] data = new byte[in.available()];
        in.read(data);
        return data;
    }

    public static InputStream convertStringToInputStream(String input) throws IOException {
        return new ByteArrayInputStream(input.getBytes(CharsetUtils.UTF8));
    }
}
